// pages/manage/clue/clue.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    screenHeight: app.globalData.screenHeight,
    userInfo:{},
    carList:{}, // 对象 页数为key，防止多次触发触底造成数据重复现象
    searchParams:{
      pageNum:1,
      pageSize:6,//默认为6
      total:0, //总条数
      pages: 0, //总页数
      queryType: 3, 
      keyword:''
    },
    noData: false,
    modalName: null,
    inputAuto: false,


    //=============
    

    onReachBottomLoading: false,
    refreshed: false, // 将本属性设置为true，收起下拉刷新，可多次设置为true（即便原来已经是true了）
    userAgreement: true,
    scopeCar:{},
    operationPageNum:0,
    closeReasonsList:['已经卖给消费者','批发给同行','收到定金了','不便透露'],
    closeReasons:'',
    topNum:0,
    cangotop: false,
    searchtype:null,
    dealerInfo:{},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    this.InitUserStatus();
  },
  // 检查一下登录状态。
  async InitUserStatus(){
      app.showLoading("获取用户信息");
      await app.checkToken();
      this.InitUserInfo();
      wx.hideLoading();
  },
  InitUserInfo(){
      // let userInfo = app.globalData.userInfo;
      this.goQuery();
      // 这里再验证一遍权限。
      // if (userInfo.roleList.indexOf('manageSecondBatch') == -1) {
      //     app.showNoAuthOrNoGrant('您无权操作查看此页面');
      //     return;
      // }else{
      //     this.goQuery();
      // }
  },
  switchType(e){
      let type = e.currentTarget.dataset.type;
      let _this = this;
      this.setData({
          'searchParams.queryType': type
      },(res)=>{
          _this.goQuery();
      })
  },
  searchParamsInput(e){
    let searchParams = this.data.searchParams;
    searchParams[e.currentTarget.dataset.name] = e.detail.value;
    this.setData({
        'searchParams':searchParams
    });
  },
  goQuery(){
    this.setData({
      'searchParams.pageNum':1,
      'searchParams.total':'',
      'searchParams.pages':'',
      'carList': {}
    });
    this.hideModal();
    this.carManageList(this.data.searchParams);
  },
  onReachBottom(){
      if (this.data.searchParams.pageNum == this.data.searchParams.pages || this.data.searchParams.pageNum > this.data.searchParams.pages) {
          //app.alert('没有更多了哦~');
      }else{
          let self = this;
          this.setData({
              'searchParams.pageNum': self.data.searchParams.pageNum+1
          });
          this.carManageList(this.data.searchParams);
      }
  },    
  carManageList(searchParams){
    app.sHttp.carManageList(searchParams).then(res=>{
        // res = {
        //   "msg":"ok",
        //   "result":{
        //     "total":3,
        //     "pages":1,
        //     "carList":[
        //       {
        //         "carId":135,
        //         "city":"北京市",
        //         "clearScore":"100",
        //         "coverUrl":"https://zzsourcecar.oss-cn-hangzhou.aliyuncs.com/car/archives/220112/097d270576df4dabacc257a097189868o.jpg?Expires=3223079216&OSSAccessKeyId=LTAI4GBcZtMnrVQ72WG22fri&Signature=q6bt9VxN%2F8fATWkZ%2Fd5BHSqsf%2BY%3D",
        //         "dealerId":100024,
        //         "engineNo":"",
        //         "lastClearTimeFormat":"刚刚发布",
        //         "licensingTimeFormat":"1个月",
        //         "mileage":2.00,
        //         "ocrPicUrl":"",
        //         "offerPriceUsers":0,
        //         "plateNo":"",
        //         "province":"北京市",
        //         "shares":0,
        //         "shortVehicleName":"测试手动填写的车型，cms控制能否展示",
        //         "status":1,
        //         "todayIsClear":1,
        //         "vehicleName":"测试手动填写的车型，cms控制能否展示",
        //         "views":12,
        //         "vin":"888",
        //         "visitorViews":0,
        //         "wholesalePrice":88.00
        //       },
        //       {
        //         "carId":56,
        //         "city":"杭州市",
        //         "clearScore":"100",
        //         "coverUrl":"https://zzsourcecar.oss-cn-hangzhou.aliyuncs.com/car/archives/211129/a969bc55b8cd49c59efa7c015c81b316o.jpg?Expires=3219306097&OSSAccessKeyId=LTAI4GBcZtMnrVQ72WG22fri&Signature=EY6%2BRm2v74blxnaleBZb%2FUAlHrQ%3D",
        //         "dealerId":100024,
        //         "lastClearTimeFormat":"刚刚发布",
        //         "licensingTimeFormat":"3个月",
        //         "mileage":2.00,
        //         "offerPriceUsers":0,
        //         "province":"浙江省",
        //         "shares":0,
        //         "shortVehicleName":"2013款 一汽奥迪 一汽奥迪A4 三厢 2.0T CVT 标准型",
        //         "status":1,
        //         "todayIsClear":1,
        //         "vehicleName":"2013款 一汽奥迪 一汽奥迪A4 三厢 2.0T CVT 标准型",
        //         "views":23,
        //         "vin":"LFV3A28K3D308084d",
        //         "visitorViews":0,
        //         "wholesalePrice":88.00
        //       },
        //       {
        //         "carId":137,
        //         "city":"天津市",
        //         "clearScore":"100",
        //         "coverUrl":"https://zzsourcecar.oss-cn-hangzhou.aliyuncs.com/car/archives/220113/d6b42cad7b50412c9560b30392755e8fo.jpg?Expires=3223163823&OSSAccessKeyId=LTAI4GBcZtMnrVQ72WG22fri&Signature=iqyioDGB4O4cN8VSHZUN5iqd2cY%3D",
        //         "dealerId":100024,
        //         "engineNo":"",
        //         "lastClearTimeFormat":"刚刚发布",
        //         "licensingTimeFormat":"1个月",
        //         "mileage":2.00,
        //         "ocrPicUrl":"",
        //         "offerPriceUsers":0,
        //         "plateNo":"",
        //         "province":"天津市",
        //         "shares":0,
        //         "shortVehicleName":"测试一口价",
        //         "status":1,
        //         "todayIsClear":1,
        //         "vehicleName":"测试一口价",
        //         "views":21,
        //         "vin":"8889",
        //         "visitorViews":0,
        //         "wholesalePrice":111.00
        //       }
        //     ]
        //   },
        //   "rtn":"1",
        //   "timestamp":1645822266708
        // }
        let carList = this.data.carList;
        carList[searchParams.pageNum] = res.result.carList;

        if (0 == res.result.total) {
          this.setData({
            'noData': true
          })
        }else{
            this.setData({
                'noData': false,
                'carList': carList,
                'searchParams.total':res.result.total,
                'searchParams.pages': res.result.pages
              });
        }
      },err=>{
        app.error(err.msg);
      })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target,
      inputAuto: true,
      'searchParams.keyword':''
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null,
      inputAuto: false
    })
  },

  //========================
  showShareModal(){
    if(this.data.scopeCar.dealerId){
      app.sHttp.dealerInfo({dealerId:this.data.scopeCar.dealerId}).then(res =>{
        this.setData({
            'dealerInfo': res.result
        });
        this.selectComponent('#posterComponent').showShareModal('');
    },err=>{
      app.error(err.msg);
    })
    }else{
      this.selectComponent('#posterComponent').showShareModal('');
    }
    // app.sHttp.shareqrCode({pageUrl:'pages/card/card',scene:'cid='+car.carId}).then(res =>{
    //   let userQrcode = 'data:image/png;base64,' + res.base64;

    // },err=>{
    //   app.error(err.msg);
    // });
  },
  seeBids(){
    let car = this.data.scopeCar;
    this.hideModal();
    wx.navigateTo({
      url: '/pages/garage/offerPrice/offerPrice?cid='+car.carId,
    })
  },
  // 降价一口价
  secondBatch(){
    let car = this.data.scopeCar;
    app.globalData.atttionCar = car;
    this.hideModal();
    wx.navigateTo({
      url: '/pages/garage/secondBatch/secondBatch?cid=' + car.carId,
    })
  },
  // 重新上架
  reShelving(){
    app.sHttp.carManageModifyStatus({carId:this.data.scopeCar.carId,status:1}).then(res =>{
      this.hideModal();
      app.success('上架成功~');
      let self = this;
      setTimeout(() => {
        self.carManageList({pageNum:self.data.operationPageNum,pageSize:6,status:self.data.searchParams.status,keyword:self.data.searchParams.keyword});
      }, 1000);
    },err=>{
      app.error(err.msg);
    })
  },
  // 下架弹窗
  showOffTheShelf(e){
    let car = e.currentTarget.dataset.car;
    if (car.status != 1) {
      this.setData({
        'scopeCar': car
      })
      this.showShareModal();
    }else{
      this.setData({
        'scopeCar': car,
        'operationPageNum': e.currentTarget.dataset.pagenum,
        'modalName': 'offTheShelf'
      });
    }
  },
  offTheShelf(){
    if("" == this.data.closeReasons){
      app.alert('请选择下架原因');
      return;
    }
    app.sHttp.carManageModifyStatus({carId:this.data.scopeCar.carId,status:2,closeReasons:this.data.closeReasons}).then(res =>{
      this.hideModal();
      app.success('下架成功~');
      let self = this;
      if(self.data.userAgreement){
        this.showShareModal();
      }
      setTimeout(() => {
        self.carManageList({pageNum:self.data.operationPageNum,pageSize:6,status:self.data.searchParams.status,keyword:self.data.searchParams.keyword});
      }, 1000);
    },err=>{
      app.error(err.msg);
    })
  },
  carManageDetail(){
    let car = this.data.scopeCar;
    this.hideModal();
    wx.navigateTo({
      url: '/pages/garage/carDetail/carDetail?cid=' + car.carId,
    })
  },
  // 跳转到车辆详情页面
  jumpToCardInfo(e){
    let cid = e.currentTarget.dataset.cid;
    wx.navigateTo({
      url: '/pages/card/card?cid=' + cid+'&self=selfCar',
    })
  },
  
  carManageClearCar(e){
    let pageNum = e.currentTarget.dataset.pagenum;
    let index = e.currentTarget.dataset.idx;
    let carId = e.detail;
    if (0 == carId) {
      app.error('请关闭重试');
      return;
    };
    app.sHttp.carManageClearCar(carId).then(res =>{
      let carList = this.data.carList;
      carList[pageNum][index].clearScore = 100;
      carList[pageNum][index].todayIsClear = 1;
      this.setData({
        'carList':carList
      });
      // 重播动画
      this.selectComponent('#barpie'+carId).reloadAnimation();
      // this.goQuery();
    },err=>{
      app.error(err.msg);
    })
  },
  // 管理车辆
  manageCar(e){
    this.setData({
      'scopeCar': e.currentTarget.dataset.car,
      'operationPageNum': e.currentTarget.dataset.pagenum,
      'modalName': 'manageCar'
    });
  },
  useUserAgreement(){
    this.setData({
      userAgreement: !this.data.userAgreement
    })
  },
  chooseReasons(e){
    this.setData({
      'closeReasons': e.currentTarget.dataset.content
    })
  },
  jumpToRizhi(e){
    wx.navigateTo({
      url: '/pages/manage/journal/journal?id='+e.currentTarget.dataset.id,
    })
  },
})